package com.example.homework0113;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<ChatModel>msgData;

    public void setMsgData(List<ChatModel> msgData) {
        this.msgData = msgData;
    }

    private Context context;

    public ChatAdapter(Context context) {
        this.context = context;
    }

    private final int CHAT_MSG_ITEM_SEND=0Xf1;
    private final int CHAT_MSG_ITEM_RECVE=0Xf1-1;

    //如果条目类型很多，需要声明条目类型常量标识
  @Override
    public int getItemViewType(int position) {
      //true为发送，false为接收
      if (msgData.get(position).isSendorRecve()){
          return CHAT_MSG_ITEM_SEND;
      }else {
          return CHAT_MSG_ITEM_RECVE;
      }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      switch (viewType){
          case CHAT_MSG_ITEM_SEND:
              return new sendHolder(LayoutInflater.from(context).inflate(R.layout.chat_itew_send,null));
          case CHAT_MSG_ITEM_RECVE:
              return new recveHolder(LayoutInflater.from(context).inflate(R.layout.chat_item_recve,null));
      }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
      switch (getItemViewType(position)){
          case CHAT_MSG_ITEM_SEND:{
              ((sendHolder)holder).sendIcon.setImageResource(msgData.get(position).getUserIcon());
              ((sendHolder)holder).sendText.setText(msgData.get(position).getTextMsg());
              break;
          }
          case CHAT_MSG_ITEM_RECVE:{
              ((recveHolder)holder).recveIcon.setImageResource(msgData.get(position).getUserIcon());
              ((recveHolder)holder).recveText.setText(msgData.get(position).getTextMsg());
              break;
          }
      }

    }

    @Override
    public int getItemCount() {
        return null!=msgData?msgData.size():0;
    }
    class sendHolder extends RecyclerView.ViewHolder{
        ImageView sendIcon;
        TextView sendText;

        public sendHolder(@NonNull View itemView) {

            super(itemView);
            sendIcon=itemView.findViewById(R.id.send_icon);
            sendText=itemView.findViewById(R.id.send_text);
        }
    }
    class recveHolder extends RecyclerView.ViewHolder{
        ImageView recveIcon;
        TextView recveText;

        public recveHolder(@NonNull View itemView) {
            super(itemView);
            recveIcon=itemView.findViewById(R.id.recve_icon);
            recveText=itemView.findViewById(R.id.recve_text);

        }
    }
}
